package com.tina.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * @Author tina
 * @Time 2020/11/29 下午3:31
 * @Version 1.0
 * @Content 邮件发送 工具类
 **/
@Component
@Slf4j
public class MailUtil {

    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    TemplateEngine templateEngine;

    /**
     * 发送者
     */
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送邮件
     *
     * @param to       接收者
     * @param title    标题
     * @param mailTemp 模板
     * @param context  内容 key-value
     */
    public void sendMail(String to, String title, String mailTemp, Context context) {
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg);
        try {
            helper.setTo(to);
            helper.setFrom(from);
            helper.setSubject(title);
            helper.setSentDate(new Date());
            String mail = templateEngine.process(mailTemp, context);
            helper.setText(mail, true);
            javaMailSender.send(msg);
            log.info(":邮件发送成功");
        } catch (MessagingException e) {
            e.printStackTrace();
            log.error("邮件发送失败：" + e.getMessage());
        }
    }

}
